package com.sbtr.common.advice;

import com.sbtr.common.Response;
import com.sbtr.common.ResultCodeCanstant;
import com.sbtr.exception.BDException;
import com.sbtr.exception.BizException;
import com.sbtr.security.common.exception.CusSecurityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;

/**
 * 统一异常处理
 *
 * @author oujh5
 */
@Configuration
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    public Response<?> handleException(Exception e, HttpServletResponse response) {
        logger.error("请求异常", e);
        if (e instanceof MethodArgumentNotValidException) {
            String message = processValiMsg((MethodArgumentNotValidException) e);
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
        } else if (e instanceof BizException) {
            return Response.error(((BizException) e).getCode(), ((BizException) e).getRawMessage());
        }
        return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(BDException.class)
    public Response<?> handleException(BDException e) {
        logger.error("请求异常", e);
        return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(CusSecurityException.class)
    public Response<?> handleException(CusSecurityException e) {
        logger.error("权限异常", e);
        return Response.error(e.getCode(), e.getMessage());
    }


    /**
     * 获取validation注解校验的提示语
     *
     * @param e - 异常对象
     * @return 提示语
     * @author qiujun
     * @date 2019-11-5
     */
    private String processValiMsg(MethodArgumentNotValidException e) {
        Iterator<?> var2 = e.getBindingResult().getAllErrors().iterator();
        while (var2.hasNext()) {
            ObjectError error = (ObjectError) var2.next();
            return error.getDefaultMessage();
        }
        return ResultCodeCanstant.SYSTEN_ERROR.getReasonPhrase();
    }

}
